import { openDB } from "idb";

let dbInstance: any = null;

const initDB = async () => {
  if (!dbInstance) {
    dbInstance = await openDB("kvDB", 1, {
      upgrade(db) {
        if (!db.objectStoreNames.contains("kvStore")) {
          db.createObjectStore("kvStore", { keyPath: "key" });
        }
      }
    });
  }
  return dbInstance;
};

export const useKeyValueStore = () => {
  const getValue = async (key: string) => {
    const db = await initDB();
    const entry = await db.get("kvStore", key);
    return entry?.value;
  };

  const setValue = async (key: string, value: any) => {
    const db = await initDB();
    await db.put("kvStore", { key, value });
  };

  return { getValue, setValue };
};
